package GUI;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JTable;

import java.awt.Font;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextPane;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.BevelBorder;
import javax.swing.JCheckBox;
import javax.swing.JButton;

import Client.BusinessImplements;
import Controler.Member_Card_Controler;
//import Controler.Order_Item_controler;
import Controler.Search_Result_Controler;
import DAL.Member_DAL;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.awt.SystemColor;
import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.swing.border.LineBorder;

public class Search_Result extends Abstract_Jpanel {

	
	/**
	 *  showing the results of all the Item that you looked
	 */
	private ArrayList<String> ansFromSearchResult = new ArrayList<String>();
	public JButton btnDetails;
	public JButton btnOrderItem;
	public JButton btnBack;
	private JTable table;
	private JLabel lblNewLabel;
	private final JPanel panel_1 = new JPanel();
	private final JScrollPane scrollPane = new JScrollPane();
	private JLabel label;
	private Object[][] data; 
	private final JPanel panel = new JPanel();
	private String decoded = new String();
	public Search_Result() {
		
		reasultGui();

	}
	private void reasultGui() {
		setLayout(null);
		panel_1.setBorder(new LineBorder(new Color(153, 180, 209), 7));
		panel_1.setBackground(SystemColor.inactiveCaption);
		panel_1.setBounds(10, 49, 1081, 580);
		
		add(panel_1);
		panel_1.setLayout(null);
		scrollPane.setViewportBorder(new LineBorder(SystemColor.activeCaption, 4));
		scrollPane.setBounds(30, 56, 1002, 478);
		panel_1.add(scrollPane);
		
		 lblNewLabel = new JLabel("");
		lblNewLabel.setFont(new Font("MV Boli", Font.BOLD, 20));
		lblNewLabel.setBounds(30, 11, 719, 45);
		panel_1.add(lblNewLabel);
		
		JLabel lblItemSearchResult = new JLabel(" Search Item Result:");
		lblItemSearchResult.setForeground(new Color(25, 25, 112));
		lblItemSearchResult.setBounds(10, 11, 351, 37);
		lblItemSearchResult.setFont(new Font("MV Boli", Font.BOLD, 30));
		add(lblItemSearchResult);
		panel.setBounds(42, 640, 1014, 59);
		
		add(panel);
		panel.setLayout(null);
		
		
		
		 btnBack = new JButton("Back");
		 btnBack.setFont(new Font("Tahoma", Font.PLAIN, 14));
		 btnBack.setBounds(10, 11, 89, 37);
		 panel.add(btnBack);
		 
		 
		 
		 
		 
		 btnDetails = new JButton("Details");
		 btnDetails.setFont(new Font("Tahoma", Font.PLAIN, 14));
		 btnDetails.setBounds(890, 12, 89, 36);
		 panel.add(btnDetails);
		 
		 		btnOrderItem = new JButton("Order Item");
		 		btnOrderItem.setFont(new Font("Tahoma", Font.PLAIN, 14));
		 		btnOrderItem.setBounds(466, 11, 105, 34);
		 		if (BusinessImplements.GetInstance().getUserLogin().getUserPosition()==1) //user
		 		panel.add(btnOrderItem);
		 		btnOrderItem.addActionListener(new ActionListener() {
		 			public void actionPerformed(ActionEvent e) {
		 				Sign_in_panel sip=new Sign_in_panel();
		 				on_screen_unload();
		 				orderItem();
		 				BusinessImplements.GetInstance().getMainFrame().setContentPane(sip);
		 				sip.setSize(getMaximumSize());
		 				sip.on_screen_load();
		 			}
		 		});
		 btnDetails.addActionListener(new ActionListener() {
		 	public void actionPerformed(ActionEvent e) {
		 		Search_Result_Controler src = new Search_Result_Controler();
		 		int r=table.getSelectedRow();
				if (r == -1)
				{
					JOptionPane.showMessageDialog(null,"You have not selected anything");
				}
				else
				{
					
					String itemId = (String) data[r][0];
					
					/**
					 * here we will take the string from DB and convert it back to Pdf
					 */
			 		decoded = src.getDescription(itemId);
			 			byte[] encoded = null;
						try {
							encoded = decoded.getBytes("ISO-8859-1");
						} catch (UnsupportedEncodingException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} //String to getting to server
			            FileOutputStream fos = null;
						try {
							fos = new FileOutputStream("temp\\Description.pdf");
						} catch (FileNotFoundException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
			            try {
							fos.write(encoded);
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
			            try {
							fos.close();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
			 		try {
			 			 
			 			if (true) {
			 	 /**
			 	  * here we will open the PDF that we get from the db
			 	  */
			 				Process p = Runtime
			 				   .getRuntime()
			 				   .exec("rundll32 url.dll,FileProtocolHandler temp\\Description.pdf");
			 				p.waitFor();
			 	 
			 			} 
			 	 
			 			System.out.println("Done");
			 	 
			 	  	  } catch (Exception ex) {
			 			ex.printStackTrace();
			 		  }
		 	}
		 	}
		 });
		 btnBack.addActionListener(new ActionListener() {
		 	public void actionPerformed(ActionEvent e) {
		 		Sign_in_panel sip=new Sign_in_panel();
		 		on_screen_unload();
		 		BusinessImplements.GetInstance().getMainFrame().setContentPane(sip);
		 		sip.setSize(getMaximumSize());
		 		sip.on_screen_load();
		 		
		 		
		 		
		 	}
		 });
		
		
	}
	@Override
	public void next_screen() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void prev_screen() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void on_screen_load() {
		// TODO Auto-generated method stub
		update_table();

	}
	@Override
	public void on_screen_unload() {
		// TODO Auto-generated method stub 
		
		
	}
	/**
	 * this method building table by the quary from db
	 */
	public void update_table(){
		String[] columnNames = {"item ID","item Name", "Num Of Copies", "edition", "Duration of lending", "description", "location", "Num Of Aviliable", "Num Of Ordered"};
		String[] line;
		int S=ansFromSearchResult.size();
		int c,r;
		
		if (ansFromSearchResult.get(0) == null)
			S=0;
 
		lblNewLabel.setText("The Systen found "+S+" result");
	
		
		data = new Object[S][9];
		
		for (r=0; r<S; r++)
		{

			line = ansFromSearchResult.get(r).split(",");
			for (c=0; c<9; c++)
				if (c == 4)
				{
					if ( line[c].equals("0") )
						data[r][c] = "3 days";
					if ( line[c].equals("1") )
						data[r][c] = "2 weeks";
				}
				else
					data[r][c] = line[c];
		}
		table = new JTable(data,columnNames);
		scrollPane.setViewportView(table);
		
	
	}
	public void save_answer(ArrayList<String> ans1) {
		ansFromSearchResult = ans1; 
		
	}
	/**
	 * this method handle with the order of item that been ordered 
	 */
	public void orderItem() {
		int r;
		String name, item, date,Aviliable; 
		Date d = new Date();
		Search_Result_Controler oic = new Search_Result_Controler();
		date = d.toString();
		r=table.getSelectedRow();
		if (r == -1)
		{
			JOptionPane.showMessageDialog(null,"You have not selected anything");
		}
		
		Aviliable = (String) data[r][7];
		if ( !(Aviliable.equals("0")) )
		{
 			JOptionPane.showMessageDialog(null, "There is enough Item to lend" );
 			return;
 		}
			
		item = (String) data[r][0];
		Member_Card_Controler mhc=new Member_Card_Controler();
 		Member_DAL member=mhc.checkID(  Integer.toString(BusinessImplements.GetInstance().getUserLogin().getUserID()));
 		if (member==null)
 		{
 			JOptionPane.showMessageDialog(null, "The user didn't exist in the system" );
 			return;
 		}
 		if ( !(member.getStatus().equals("0")) )
 			JOptionPane.showMessageDialog(null,"ERROR -you have problem with your status");
 		
		
		if (BusinessImplements.GetInstance().getUserLogin().getUserPosition() == 0 )
		{
			JOptionPane.showMessageDialog(null,"ERROR -You have to be registered member");
			return ;
		}
		else
		{
			name =  Integer.toString(BusinessImplements.GetInstance().getUserLogin().getUserID());
			if ( oic.doesOrderAllow(item, name) )
			{
				if(oic.puttingOrder(name, item))
				{
					JOptionPane.showMessageDialog(null,"The Item been ordered"); 
					return ;
				}
				else 
					JOptionPane.showMessageDialog(null,"You have not been allowed to make an order");
			}
			else
			{
				JOptionPane.showMessageDialog(null,"ERROR - impossible to make order");
				return ;
			}
		}
		
	}
}
